<template>
    <Layout class="login-container">
        <Header>
            <BHeader :showRegisterNow="true"></BHeader>
        </Header>
        <Content>
            <div class="login-main">
                <div class="login-content">
                    <div class="login-area">
                        <h1>用户登录</h1>
                        <Form class="login-form" ref="form" :model="form" :rules="rules">
                            <Form-item prop="user">
                                <Input type="text" ref="user" v-model.trim="form.user" size="large" placeholder="账号" @on-enter="login">
                                    <i class="icon iconfont icon-yonghu" slot="prepend"></i>
                                </Input>
                            </Form-item>
                            <Form-item prop="password">
                                <Input type="password" ref="password" v-model.trim="form.password" size="large" :minlength="6" placeholder="密码" @on-enter="login">
                                    <i class="icon iconfont icon-mima" slot="prepend"></i>
                                </Input>
                            </Form-item>
                            <Form-item prop="captcha">
                                <Row :gutter="24">
                                    <Col span="12"><Input type="text" v-model.trim="form.captcha" size="large" style="width:150px" :maxlength="4" placeholder="验证码" @on-enter="login">
                                        <i class="icon iconfont icon-yanzhengma" slot="prepend"></i>
                                    </Input></Col>
                                    <Col span="7"><div class="captcha" ref="captcha" @click="getCaptcha">加载中...</div></Col>
                                    <Col span="4" class="change-captcha">
                                        <div @click="getCaptcha">
                                            <i class="icon iconfont icon-shuaxin"></i>
                                        </div>
                                    </Col>
                                </Row>  
                            </Form-item>           
                            <Form-item>
                                <Button type="primary" @click="login" :loading="loading" long>登录</Button>
                            </Form-item>
                            <a href="javascript:void(0)" class="forget-password" @click="toForgetPassword">忘记密码</a>
                        </Form>
                    </div>
                </div>
            </div>
        </Content>
        <Footer>
            <BFooter :isLine="false"></BFooter>
        </Footer>
    </Layout>
</template>
<script>
    import BHeader from 'components/BHeader'; //页头
    import BFooter from 'components/BFooter'; //页脚
    import {Storage} from '@/commons/js/utils';
    export default {
        components: { BHeader,BFooter },
        data(){
            const validateUser = (rule, value, callback) => {
                if (!value) return callback(new Error('请输入道路运输经营许可证号或手机号'));                
                else if(!this.$utils.RegexUtils('USERNAME',value)) return callback(new Error('请输入正确的道路运输经营许可证号或手机号'));
                else if(value.length == 11) {//11位数时，检验手机号是否注册
                    this.$ajax(this.$api.common.userCheck,{"mobile": this.form.user},(RES)=>{
                        if(RES.code == 404) return callback(new Error('该手机号尚未注册或绑定，请先注册。'));
                        else callback();
                    },(error)=>{
                        callback();  
                    })
                }
                else if(value.length == 12) {//12位数时，检验道路运输许可证号是否注册
                    this.$ajax(this.$api.common.userCheck,{"licenseNo": this.form.user},(RES)=>{
                        if(RES.code == 404) return callback(new Error('该道路运输许可证号尚未注册或绑定，请先注册。'));
                        else callback();
                    },(error)=>{
                        callback();  
                    })
                }
                else callback();
            };
            const validateCaptcha = (rule, value, callback) => {
                if (!value) return callback(new Error('请输入验证码'))
                else if(value.toLocaleLowerCase() !== this.captcha.toLocaleLowerCase()){
                    this.getCaptcha();
                    callback(new Error('验证码错误，请重输'))
                }else callback();
            };
            return{
                loading: false,//是否正在登录
                captchaLogin: false,//是否正在加载验证码
                captcha: '',//验证码的值
                form: {
                    user: '',//账户名
                    password: '',//密码
                    captcha: '',//验证码
                },
                rules: {
                    user: [
                        { validator: validateUser, trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { type: 'string', min: 6, message: '密码不能少于6位', trigger: 'blur' },                   
                        { type: 'string', max: 16, message: '密码不能多于16位', trigger: 'blur' }                    
                    ],
                    captcha: [
                        { validator: validateCaptcha, trigger: 'blur' }
                    ]
                },
            }
        },
        created() {
            Storage.remove('B_TOKEN');//用户token
            Storage.remove('B_ACCOUNT');//用户账号信息
            Storage.remove('B_MENU_STATE');//导航伸缩状态
            Storage.remove('B_BROWSER');//删除本地 是否提示更新浏览器
        },
        mounted(){
            this.init();
        },
        methods:{
            init() {
                this.form.user = Storage.getItem('B_USER');//设置登录账号名
                this.getCaptcha('created');
                // this.$utils.CommonUtils.getBrowserVersion()
                // this.$store.commit('updateBrowser', Storage.getObj('B_BROWSER'));
                // Storage.setObj('browser', this.$utils.CommonUtils.getBrowserVersion());
            },
            getCaptcha(type) {
                if(this.captchaLogin) return;//如果正在加载验证码，则不做任何操作

                //设置验证码相关初始状态
                this.form.captcha = '';
                this.captchaLogin = true;
                this.$refs.captcha.innerHTML = '加载中...';

                //获取后端验证码
                this.$ajax(this.$api.login.captcha,'',(RES)=>{
                    //设置验证码返回值
                    this.captcha = RES.text;
                    this.$refs.captcha.innerHTML = RES.data;
                    this.captchaLogin = false;
                },(error)=>{
                    this.captchaLogin = false;
                    this.$refs.captcha.innerHTML = '加载失败';
                    this.$Message.error('服务器出错');
                })
            },
            login() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        //验证通过则调用登录接口
                        this.loading = true;
                        this.$ajax(this.$api.login.login,{
                            "mobile": this.form.user,
                            "password": this.form.password
                        },(RES)=>{
                            /*后端返回值相关：
                            {code: 451, msg: "Mobile required"}
                            {code: 453, msg: "Password required"}
                            {code: 455, msg: 'Account not registered'}
                            {code: 456, msg: 'Invalid password'}
                            {code: 500, msg: err}
                            {code: 200, msg: "Success"}*/

                            this.loading = false;
                            Storage.remove('B_TOKEN');
                            console.log(RES);

                            //登录成功前往对应页面
                            if(RES.code == 200){
                                Storage.setItem('B_TOKEN',RES.token);//设置token
                                Storage.setItem('B_USER',this.form.user);//设置登录账号名
                                this.$utils.Storage.setObj('B_ACCOUNT', RES.data);

                                let status = RES.data.company.status;//公司状态,1:审核中，2:审核失败, 3:审核成功
                                //审核中，前往等待审核页面
                                if(status && status == 1){
                                    this.$router.push('/settleProgress?status=1');
                                }
                                //审核失败，前往修改入驻信息页面
                                else if(status && status == 2){
                                    let id = RES.data.company._id;
                                    this.$router.push('/settleFail?id='+id);
                                }
                                //审核通过，需判断有没有门店
                                else if(status && status == 3){
                                    //如果没有门店信息，则前往新增门店页面
                                    if(!RES.data.store._id){
                                        this.$router.push('/addStore')
                                    }
                                    //全部信息完整时进入首页
                                    else{
                                        this.$utils.Storage.remove('B_MENU_STATE'); //删除本地菜单展开状态
                                        this.$router.push('/index');
                                    }
                                }
                                //后台管理系统新建的账号，但未入驻信息
                                else{
                                    this.$Message.error('账号信息有误，请联系管理员');
                                }
                            }
                            else if(RES.code == 455) {
                                this.$Message.error('该账号未注册');
                                this.$refs.user.focus();
                                this.getCaptcha();
                            }
                            else if(RES.code == 456) {
                                this.$Message.error('密码错误');
                                this.$refs.password.focus();
                                this.getCaptcha();
                            }
                            else if(RES.code == 500) {
                                this.$Message.error('数据库出错');
                            }
                            else this.$Message.error(RES.msg);
                        },(error)=>{    
                            console.log(error);
                            this.loading = false;
                            this.$Message.error('服务器出错');
                        })
                    }
                })
            },
            toRegister() {
                this.$router.push('/settle');
            },
            toForgetPassword() {
                this.$router.push('/forgetPassword');
            }
        }
    }
</script>

<style lang="less" rel="stylesheet/less">
    .login-container{
        position: absolute;
        width: 100%;
        height: 100%;
        min-height: 600px;
        .ivu-layout-content{
            position: relative;
        }
        .login-main{
            position: absolute;
            width: 100%;
            height: 100%;
            min-width: @min-width;
            background: url('/static/images/login-bg.jpg') no-repeat;
            background-position: center;
            background-size: cover;
            .login-content{
                position: relative;
                width: @min-width;
                height: 100%;
                margin: 0 auto;
            }

            .login-area{
                position: absolute;
                right: 80px;
                width: 380px;
                height: 400px;
                top: 50%;
                transform: translateY(-50%);
                padding: 40px;
                background-color: #fff;

                h1{
                    font-size: 20px;
                    color: @color-Title;
                    margin-bottom: 30px;
                }
            }

            .icon.iconfont{
                font-size: 14px;
                color: @color-Disabled;
                padding-right: 15px;
                padding-left: 15px;
            }

            .ivu-input-group .ivu-input{
                padding-left: 44px !important;
                border-radius: 4px !important;
            }

            .ivu-input-group-prepend{
                position: absolute;
                left: 0;
                top: 0;
                bottom: 0;
                padding: 0;
                width: 44px;
                height: 40px !important;
                line-height: 40px !important;
                background-color: transparent !important;
                z-index: 3;
                padding-right: 0;
                border: none;
            }

            .captcha{
                width: 100px;
                height: 40px;
                text-align: center;
                cursor: pointer;
                padding-top: 2px;

                svg{
                    max-height: 40px;
                }
            }

            .change-captcha{
                height: 34px;
                line-height: 40px;
                text-align: right;
                .icon.iconfont{
                    font-size: 25px;
                    color: @color-Primary;
                    cursor: pointer;
                    padding-right: 0;
                }
            }

            .forget-password{
                color: @color-Content;
            }

            .ivu-form-item{
                margin-bottom: 20px;
            }
        }
    }
</style>